<?php

namespace app\admin\model;

use think\Model;
use app\mpbase\library\WechatCard;
use think\Db;

class ConsumeCard extends Model
{
    // 表名
    protected $name = 'consume_card';
    
    // 自动写入时间戳字段
//    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
//    protected $createTime = 'createtime';
//    protected $updateTime = false;
    
    // 追加属性
    protected $append = [

    ];
    

    


    public  static function consume($data)
    {
        //查看核销员mp_openid是否已经存在
        if($cancel = Db::table('uct_store_cancel')->where(['mp_openid' => $data->StaffOpenId])->find()){
            $store_id = $cancel['store_id'];
        }else{
            $card = new WechatCard();
            $user = $card->app->user;
            $userinfo = $user->get($data->StaffOpenId);
            Db::table('uct_store_cancel')->where(['unionid' => $userinfo->unionid])->update(['mp_openid' => $userinfo->openid]);
            $cancel = Db::table('uct_store_cancel')->where(['mp_openid' => $data->StaffOpenId])->find();
            $store_id = $cancel['store_id'];
        }

        $consume_card = self::create([
            'user_openid'    => $data->FromUserName,
            'card_id'        => $data->CardId,
            'code'           => $data->UserCardCode,
            'consume_openid' => $data->StaffOpenId,
            'createtime'     => $data->CreateTime,
            'cancel_store_id' => $store_id
        ]);


        $cardinfo = Db::table('uct_wechat_card')->alias('card')
            ->join('uct_admin admin','admin.id = card.admin_id')
            ->where(['card.card_id' => $data->CardId])
            ->field(['admin.type','card.status','card.business_price','card.store_id'])
            ->find();

        //判断卡券是否广告商，是否已经删除了。如果是则扣除广告位的相应金额
        if($cardinfo['type'] == 2 && $cardinfo['status'] == 'CARD_STATUS_DELETE'){
            Db::table('uct_hk_store')->where(['id' => $cardinfo['store_id']])->setDec('banlance',$cardinfo['business_price']);
            file_put_contents('./test30','jintian');
        }
    }




}
